package HandshakeJoin;

import java.util.Calendar;
import com.google.common.base.Joiner;
import org.apache.s4.base.Event;

public class QueryRequest extends Event
{
    public static enum Type {
        ONE_TIME, CONTINUOUS, UNKNOWN
    }

    public static enum Subtype {
        EQUAL_BY_JOIN_KEY,
        RANGE_BY_JOIN_KEY,
        EQUAL_BY_TIMESTAMP,
        RANGE_BY_TIMESTAMP,
        UNKNOWN
    }

    private String clientId;
    private Type type;
    private long reqTimestamp;
    private Subtype subtype;

    QueryRequest() {}

    QueryRequest(final String clientId, final String joinId, final Type type) {
        this.clientId = clientId;
        put("joinId", String.class, joinId);
        this.type = type;
        reqTimestamp = Calendar.getInstance().getTimeInMillis();
    }

    public QueryRequest setArgument(final String argName,
            final String valueString) {
        put(argName, String.class, valueString);

        return this;
    }

    public String getArgument(final String argName) {
        return get(argName);
    }

    public String getClientId() {
        return clientId;
    }

    public String getJoinId() {
        return get("joinId");
    }

    public Type getType() {
        return type;
    }

    public String getTypeAsString() {
        String typeString;
        switch (type) {
        case ONE_TIME:
            typeString = "one-time";
            break;

        case CONTINUOUS:
            typeString = "continuous";
            break;

        default:
            typeString = "unknown";
            break;
        }

        return typeString;
    }

    public Subtype getSubtype() {
        return subtype;
    }

    public QueryRequest setSubtype(final Subtype subtype) {
        this.subtype = subtype;

        return this;
    }

    public long getRequestTimestamp() {
        return reqTimestamp;
    }

    public String getRequestId() {
        Joiner joinerUnderline = Joiner.on("_").skipNulls();
        return joinerUnderline.join(clientId, getJoinId(),
                Long.toString(reqTimestamp));
    }

    public String toString() {
        Joiner joinerComma = Joiner.on(", ").skipNulls();

        return "Req: "
                + joinerComma.join(clientId, getJoinId(), getTypeAsString(),
                        Long.toString(reqTimestamp));
    }
}